<template>
  <a-spin :spinning="spinning" tip="批量操作中">
    <a-card title="官方搭配">
      <a-tabs @change="tabChange" :activeKey="type">
        <a-tab-pane :key="item.type" :tab="item.name" v-for="item in tabs"></a-tab-pane>
      </a-tabs>
      <div class="table-page-search-wrapper">
        <a-row :gutter="20">
          <a-col :span="24">
            <a-form layout="inline" :form="form" @submit="handleSubmit">
              <a-col :xxl="6" :xl="6" :lg="12" :sm="24">
                <a-form-item label="主款款号">
                  <a-input placeholder="输入主款款号搜索" v-decorator="['productNoMain']"></a-input>
                </a-form-item>
              </a-col>
              <a-col :xxl="6" :xl="6" :lg="12" :sm="24">
                <a-form-item label="搭配款款号">
                  <a-input placeholder="输入搭配款号搜索" v-decorator="['productNoModel']"></a-input>
                </a-form-item>
              </a-col>
              <a-col :xxl="6" :xl="6" :lg="12" :sm="24">
                <a-form-item label="品牌">
                  <a-select placeholder="全部" v-decorator="['brandId']">
                    <a-select-option :value="item.weid" v-for="item in brands" :key="item.weid">{{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :xxl="6" :xl="6" :lg="12" :sm="24">
                <a-form-item label="年份">
                  <a-date-picker format="YYYY" :open="openYear" @openChange="openChange" @change="handleChange"
                    mode="year" @panelChange="panelChange" :value="year" />
                </a-form-item>
              </a-col>
              <a-col :xxl="6" :xl="6" :lg="12" :sm="24">
                <a-form-item label="季节">
                  <a-select placeholder="全部" v-decorator="['season']">
                    <a-select-option :value="item" v-for="(item, index) in seasons" :key="item.id">
                      {{ item }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :xxl="6" :xl="6" :lg="12" :sm="24">
                <a-form-item label="波段(月)">
                  <a-select placeholder="全部" v-decorator="['bandMonth']">
                    <a-select-option :value="item" v-for="(item, index) in months" :key="`m-${item}`">
                      {{ `${item}月` }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :xxl="6" :xl="6" :lg="12" :sm="24">
                <a-form-item label="波段">
                  <a-select placeholder="全部" v-decorator="['bands']">
                    <a-select-option :value="item" v-for="(item, index) in ['A', 'B', 'C']" :key="`m-${item}`">
                      {{ `${item}` }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :xxl="6" :xl="6" :lg="12" :sm="24">
                <a-form-item label="搭配风格">
                  <a-select placeholder="全部" v-decorator="['label']">
                    <a-select-option :value="item.code" v-for="item in styleOptions" :key="item.code">
                      {{ item.name }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :xxl="6" :xl="6" :lg="12" :sm="24">
                <a-form-item label="创建时间">
                  <a-range-picker format="YYYY-MM-DD" :placeholder="['开始时间', '结束时间']" v-decorator="['time']" />
                </a-form-item>
              </a-col>
              <a-col :xxl="6" :xl="6" :lg="12" :sm="24">
                <a-form-item label="排序方式">
                  <a-select  placeholder="全部" v-decorator="['productNo',{initialValue: 'time'}]">
                    <a-select-option value="time">按时间排序</a-select-option>
                    <a-select-option value="productNo">按主款排序</a-select-option>
                  </a-select>
                </a-form-item>
              </a-col>
              <a-col :xxl="12" :xl="12" :lg="12" :sm="24">
                <a-form-item>
                  <a-button type="primary" html-type="submit">搜索</a-button>
                  <a-button type="primary" @click="resetForm" style="margin-left:10px">重置</a-button>
                  <a-button type="primary" @click="$router.push(`/micromall/marketing/collocation/create?type=official`)"
                    style="margin-left:10px">新建</a-button>
                </a-form-item>
              </a-col>
            </a-form>
          </a-col>
        </a-row>
      </div>
      <div style="padding:10px 0">
        <a-button type="primary" v-if="type == 2" :disabled="!hasSelected" style="margin-right:10px"
          @click="batch('prohibit')">批量禁用</a-button>
        <a-button type="primary" v-if="type != 2" :disabled="!hasSelected" style="margin-right:10px"
          @click="batch('open')">批量启用</a-button>
        <a-button type="primary" :disabled="!hasSelected" @click="batch('del')">批量删除</a-button>
      </div>
      <a-table bordered :columns="columns" :rowKey="record => record.id" :data-source="dataSource"
        :pagination="pagination" :scroll="{ x: true }" @change="handleTableChange" :loading="loading"
        :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }">
        <template slot="mainPicture" slot-scope="text, record">
          <img @click="prevHandle(record.mallImage)"
            :src="record.mallImage == '' ? 'https://picttype1.jnby.com/collocation/image-empty.png' : record.mallImage"
            alt="" style="width:50px;height:50px" v-if="record.mallImage" />
          <span v-else>/</span>
        </template>
        <template slot="mainParagraph" slot-scope="text, record">
          <a-tooltip>
            <template slot="title">
              {{ record.productNoMain + '|' + record.productName }}
            </template>
            <img class="goods-img" @click="prevHandle(record.image)"
              :src="record.image == '' ? 'https://picttype1.jnby.com/collocation/image-empty.png' : record.image" alt=""
              style="width:50px;height:50px" />
          </a-tooltip>
        </template>
        <span slot="labelName" slot-scope="text, record">{{ filterLable(record.labelName) }}</span>
        <template slot="collocationParagraph" slot-scope="text, record">
          <GoodsImgList :collocationGoods="record.collocationModelInfoDTOList" />
        </template>
        <template slot="actions" slot-scope="text, record">
          <a-button type="link" @click="handleEdit(record)" v-if="type != 1">编辑</a-button>
          <a-button type="link" v-if="type == 1" @click="handleEdit(record, 1)">完善</a-button>
          <a-button type="link" @click="deleteCollcation(record.id)">删除</a-button>
          <a-button type="link" @click="updateStatus(record.id, 3)" v-if="type == 2">禁用</a-button>
          <a-button type="link" @click="updateStatus(record.id, 2)" v-if="type == 3 || type == 1">启用</a-button>
        </template>
      </a-table>
      <PreviewImg :showPreviewImg.sync="showPreviewImg" :url="previewUrl"></PreviewImg>
    </a-card>
  </a-spin>
</template>
<script>
import { listMixin } from '../../util/listMixin'
import GoodsImgList from '../../components/GoodsImgList.vue'
import ChoiceLook from '../../components/ChoiceLook.vue'
import PreviewImg from '../../components/PreviewImg.vue'
import { list, getStyle, updateCollocationStatus, removeCollocation, handleNum, batchUpdateOfficial, batchDeleteOfficial, lookLabel } from '@api/micromall/collocation.js'
import { batch } from '../util'
import collocationMixin from '../collocationMixin'

const columns = [
  {
    title: '主款商城主图',
    width: 100,
    align: 'center',
    scopedSlots: { customRender: 'mainPicture' }
  },
  {
    title: '主款',
    width: 100,
    scopedSlots: { customRender: 'mainParagraph' }
  },
  {
    title: '搭配款',
    width: 200,
    scopedSlots: { customRender: 'collocationParagraph' }
  },
  {
    title: '搭配风格',
    width: 200,
    scopedSlots: { customRender: 'labelName' }
  },
  {
    title: '创建时间',
    width: 200,
    dataIndex: 'createTime'
  },
  {
    title: '操作',
    width: 200,
    scopedSlots: { customRender: 'actions' }
  }
]
const columns2 = [
  {
    title: '主款商城主图',
    align: 'center',
    width: 100,
    scopedSlots: { customRender: 'mainPicture' }
  },
  {
    title: '主款',
    width: 100,
    scopedSlots: { customRender: 'mainParagraph' }
  },
  {
    title: '搭配款',
    width: 200,
    scopedSlots: { customRender: 'collocationParagraph' }
  },
  {
    title: '创建时间',
    width: 200,
    dataIndex: 'createTime'
  },
  {
    title: '操作',
    width: 200,
    scopedSlots: { customRender: 'actions' }
  }
]
export default {
  mixins: [collocationMixin],
  components: {
    GoodsImgList,
    ChoiceLook,
    PreviewImg
  },
  data() {
    return {
      type: 2,
      tabs: [
        {
          name: '已启用',
          type: 2
        },
        {
          name: '待完善',
          type: 1
        },
        {
          name: '已禁用',
          type: 3
        }
      ],
      dataSource: [],
      columns,
      visible: false,
      styleOptions: [],
      loading: false,
      perfectNum: 0,
      spinning: false,
      showPreviewImg: false,
      previewUrl: '',
    }
  },
  watch: {
    perfectNum: {
      immediate: true,
      handler: function (perfectNum) {
        if (perfectNum > 0) {
          this.$set(this.tabs[1], 'name', '待完善(' + perfectNum + ')')
        } else {
          this.$set(this.tabs[1], 'name', '待完善')
        }
      }
    },
    type: {
      immediate: true,
      handler: function (type) {
        if (type == 1) {
          this.columns = columns2
        } else {
          this.columns = columns
        }
      }
    }
  },
  computed: {
    formatLabel() {
      return function (ids) {
        const idArr = ids.split(',')
        const results = []
        this.styleOptions.forEach(item => {
          if (idArr.includes(item.id.toString())) {
            results.push(item.labelName)
          }
        })
        return results.join('/')
      }
    },
    hasSelected() {
      return this.selectedRowKeys.length > 0
    }
  },

  methods: {
    batch,
    prevHandle(url) {
      if (url) {
        this.showPreviewImg = true,
          this.previewUrl = url
      }
    },
    async batchUpdate(status) {
      const { selectedRowKeys: id } = this
      const res = await batchUpdateOfficial({ id, status })
      this.spinning = false
      if (res.code == 200) {
        this.clearKeys()
        this.reCalculatePage(1)
        this.loadData()
        this.getNum()
        this.$message.success(`批量${status == 3 ? '禁用' : '启用'}成功`)
      }

    },
    async batchDelete() {
      const { selectedRowKeys: id } = this
      const res = await batchDeleteOfficial({ id })
      this.spinning = false
      if (res.code == 200) {
        this.$message.success('批量删除成功')
        this.clearKeys()
        this.visible = false
        this.reCalculatePage(1)
        this.loadData()
        this.getNum()
      }
    },
    onSelectChange(selectedRowKeys) {
      console.log('selectedRowKeys changed: ', selectedRowKeys)
      this.selectedRowKeys = selectedRowKeys
    },
    async getNum() {
      const res = await handleNum()
      this.perfectNum = res.data
    },
    updateStatus(id, status) {
      this.$confirm({
        title: status == 3 ? '确定禁用选中套搭配吗？' : '确定启用选中套搭配吗？',
        content: status == 3 ? '禁用后将不会出现在主款详情页' : '启用后将有可能出现在主款详情页',
        cancelText: '暂不',
        onOk: res => {
          return new Promise(async (resolve, reject) => {
            const res = await updateCollocationStatus({ id, status })
            if (res.code == 200) {
              this.reCalculatePage(1)
              this.loadData()
              this.$message.success(`${status == 3 ? '禁用' : '启用'}成功`)
              resolve(true)
            } else {
              this.$message.error(res.msg)
              reject(false)
            }
          })
        },
        onCancel() { }
      })
    },
    handleEdit(record, differencePage = 0) {
      this.$router.push({
        path: `/micromall/marketing/collocation/edit`,
        query: {
          id: record.id,
          type: 'official',
          differencePage
        }
      })
    },
    loadData(current) {
      console.log('页面路由',this.$route.path)
      if(this.$route.path != '/micromall/marketing/collocation/official') return
      // if (!this.url.list) {
      //   this.$message.error('请设置url.list属性!')
      //   return
      // }
      //加载数据 若传入参数1则加载第一页的内容
      this.loading = true
      if (current === 1) {
        this.pagination.current = 1
      }
      var params = this.getQueryParams() //查询条件
      console.log(params)
      // 增加状态
      params.type = this.type
      if(params.productNo == 'time'){
        delete params.productNo
      }
      list(params).then(res => {
        if (res.code == 200) {
          this.dataSource = res.data.records || res.data
          if (res.data.total) {
            this.pagination.total = res.data.total
          } else {
            this.pagination.total = 0
          }
        } else {
          this.$message.warning(res.msg)
        }
        this.loading = false
      })
      this.getNum()
    },
    async styleList() {
      const re = await lookLabel({ code: 'B08-A01' })
      console.log(re)
      this.styleOptions = re.data
    },
    tabChange(type) {
      this.type = type
      this.selectedRowKeys = []
      console.log('tabChange call loadData')
      // 加载第一页
      this.loadData(1)
    },
    add() { },
    async deleteCollcation(id) {
      this.$confirm({
        content: '确定删除该套搭配吗？',
        cancelText: '暂不',
        onOk: res => {
          return new Promise((resolve, reject) => {
            removeCollocation(id)
              .then(res => {
                if (res.code == 200) {
                  this.visible = false
                  this.reCalculatePage(1)
                  this.loadData()
                  this.$message.success('删除成功')
                  resolve()
                } else {
                  this.$message.success(res.msg)
                  reject()
                }
              })
              .catch(err => {
                resolve()
                console.log(err)
              })
          }).catch(() => console.log('Oops errors!'))
        },
        onCancel() { }
      })
    }
  }
}
</script>
<style scoped>
.paragraphPic {
  width: 50px;
  height: 50px;
}

.goods-img {
  width: 50px;
  height: 50px;
}

.goods-img:not(:last-child) {
  margin-right: 10px;
}
</style>
